<?php
/**
 * 消息模板
 * Created by PhpStorm.
 * User:
 * Date: 2017/4/26
 * Time: 15:07
 */

namespace App\Services;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

// qcloud ocr
use QcloudImage\CIClient;

use App\Models\StaffInfoOcrDetail;


class OcrServices
{

    public $client;

    public function __construct()
    {
        $this->client = new CIClient(
                            config('custom.qcloud_image_app_id'), 
                            config('custom.qcloud_image_secret_id'), 
                            config('custom.qcloud_image_secret_key'), 
                            config('custom.qcloud_image_bucket')
                        );
        $this->client->setTimeout(30);

    }

    private function _log($data = '', $return = false)
    {
        Log::info(sprintf('OCR: %s%s', PHP_EOL, json_encode($data, JSON_UNESCAPED_UNICODE)));
        return $return;
    }

    // 身份证
    public function handlerIdCard($file = '')
    {
        $rs = $this->client->idcardDetect([
            'files' => [$file],
        ], 0);


        if (!$rs) {
            return $this->_log('身份证解析失败！#RS');
        }

        if (!$rs = json_decode($rs, true)) {
            return $this->_log('身份证解析失败！#JSON');
        }


        if (!isset( $rs['result_list'][0] )) {
            return $this->_log('身份证解析失败！#JSON');
        }

        $data = $rs['result_list'][0];

        if (!isset($data['code']) || $data['code'] != 0) {
            return $this->_log('OCR识别失败');
        }

        // info
        $info = $data['data'];

        // save
        $this->_saveOcrData(1, $info);

        return [
            'id_card_name' => $info['name'],
            'id_card_no'   => $info['id'],
        ];

    }

    // 驾驶证
    public function handlerDrivingLicense($file = '')
    {
        $rs = $this->client->drivinglicenceDetect([
            'file' => $file,
        ], 1);

        if (!$rs) {
            return $this->_log('驾驶证解析失败！#RS');
        }

        if (!$data = json_decode($rs, true)) {
            return $this->_log('驾驶证解析失败！#JSON');
        }

        if (!isset($data['code']) || $data['code'] != 0) {
            return $this->_log('OCR识别失败');
        }

        $return = [];
        $ocrData = [];
        foreach ($data['data']['items'] as $item) {
            $ocrData[] = [
                'k' => $item['item'],
                'v' => $item['itemstring'],
            ];

            switch ($item['item']) {
                case '姓名':
                    $return['driving_license_name'] = $item['itemstring'];
                    break;

                case '证号':
                    $return['driving_license_idno'] = $item['itemstring'];
                    break;

                default:
                    break;
            }
        }

        // save
        $this->_saveOcrData(2, $ocrData);

        return $return;
    }

    // 行驶证正本
    public function handlerVehicleLicense($file = '')
    {
        $rs = $this->client->drivinglicenceDetect([
            'file' => $file,
        ], 0);

        if (!$rs) {
            return $this->_log('行驶证解析失败！#RS');
        }

        if (!$data = json_decode($rs, true)) {
            return $this->_log('行驶证解析失败！#JSON');
        }

        if (!isset($data['code']) || $data['code'] != 0) {
            return $this->_log('OCR识别失败');
        }

        $return = [];
        $ocrData = [];
        foreach ($data['data']['items'] as $item) {
            $ocrData[] = [
                'k' => $item['item'],
                'v' => $item['itemstring'],
            ];

            switch ($item['item']) {
                case '所有人':
                    $return['vehicle_license_name'] = $item['itemstring'];
                    break;

                case '号牌号码':
                case '车牌号码':
                    $return['vehicle_license_vpl'] = $item['itemstring'];
                    break;

                default:
                    break;
            }
        }

        // save
        $this->_saveOcrData(3, $ocrData);

        return $return;
    }

    // 行驶证副本
    public function handlerVehicleLicenseB($file = '')
    {
        $rs = $this->client->drivinglicenceDetect([
            'file' => $file,
        ], 2);

        if (!$rs) {
            return $this->_log('行驶证副本解析失败！#RS');
        }

        if (!$data = json_decode($rs, true)) {
            return $this->_log('行驶证副本解析失败！#JSON');
        }

        if (!isset($data['code']) || $data['code'] != 0) {
            return $this->_log('OCR识别失败');
        }

        $return = [];
        $ocrData = [];
        foreach ($data['data']['items'] as $item) {
            $ocrData[] = [
                'k' => $item['item'],
                'v' => $item['itemstring'],
            ];

            switch ($item['item']) {
                case '号牌号码':
                case '车牌号码':
                    $return['vehicle_license_b_vpl'] = $item['itemstring'];
                    break;

                case '核定载人数':
                    $return['vehicle_capacity'] = $item['itemstring'];
                    break;

                default:
                    break;
            }
        }

        // save
        $this->_saveOcrData(4, $ocrData);

        return $return;
    }


    // 保存ocrdata
    private function _saveOcrData($type, $data = [])
    {
        return StaffInfoOcrDetail::create([
            'type' => $type,
            'ocr' => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ]);
    }

}